import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/EncryptUtils.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/auth_type.dart';
import 'package:flutter_syt/datas/cards_item.dart';
import 'package:flutter_syt/datas/game_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/mine/mine_page.dart';
import 'package:flutter_syt/domain/mine/role_box.dart';
import 'package:flutter_syt/domain/widgets/common_dialog.dart';
import 'package:flutter_syt/domain/widgets/custom_dialog.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

class CertificateDataItem {
  String id;
  String name;
  CertificateDataItem(this.id, this.name);
}

@RoutePage(name: "authenticationForm")
class AuthenticationForm extends StatefulWidget {
  final String? role;
  final String? id;

  AuthenticationForm({this.role, this.id});

  @override
  _AuthenticationFormState createState() => _AuthenticationFormState();
}

class _AuthenticationFormState extends State<AuthenticationForm> {
  final _formKey = GlobalKey<FormState>();
  String country = '';
  String country_code = '';
  String family_name = '';
  String given_name = '';
  String certificate_type = 'I0001';
  String license_number = '';
  String registration_number = '';
  List<GameDataItem> nations = [];
  List<CardsItemData> certificateData = [];
  CardsItemData? selectCertificate;

  @override
  void initState() {
    if (widget.id != '1') {
      // _getNationInfo();
      _getCardsType();
    }
    var lang = appContext.storage.getString('lang');
    if (lang == 'zh') {
      certificate_type = 'I0002';
    }
    super.initState();
  }

  // Future _getNationInfo() async {
  // List<GameDataItem> nationInfo = await API.shared.game.country();
  // setState(() {
  //   nations = nationInfo;
  //   country = nationInfo[0].name;
  //   country_code = nationInfo[0].org;
  // });
  // }

  Future _getCardsType() async {
    certificateData = await API.shared.user.cards();
    for (var element in certificateData) {
      if (element.id == certificate_type) {
        selectCertificate = element;
      }
    }

    setState(() {
      certificateData = certificateData;
    });
  }

  Future _authentication() async {
    try {
      AuthTypeItemData result = await API.shared.user.authentication({
        "role": (widget.id ?? "").rsa,
        "certificate_type": certificate_type.rsa,
        'license_number': license_number.rsa,
        "registration_number": registration_number.rsa,
        "crypt_type": "rsa",
      });
      if (result.type == '3') {
        showCommonDialog(
          context,
          DialogEntity(
            '',
            Text(S.of(context).not_registered_tianfu),
            () => {
              Navigator.of(context).pop(),
            },
            () {
              customShowToast(S().standy_by);
            },
            cancelText: S.of(context).register_later,
            okText: S.of(context).register_now,
          ),
        );
      } else {
        RouteManager.push(
          context,
          RoutMapping.authenticationSecondeForm(type: result.type),
        );
      }
    } catch (e) {
      //  await UtilsOther.showCustomShowError(e);
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (e is DioError && connectivityResult != ConnectivityResult.none) {
        if (certificate_type == 'R0001') {
          showSingleDialog(
              context,
              DialogEntity(
                '',
                Text(
                  '${e.message}',
                  textAlign: TextAlign.center,
                ),
                () {
                  Navigator.of(context).pop();
                },
                () {
                  Navigator.of(context).pop();
                },
                okText: S.of(context).reenter,
              ));
          return;
        }
        customShowToast('${e.message}');
      }
    }

    // await API.shared.user.getUserInfo();
  }

  Future _submit() async {
    if (license_number.isEmpty) {
      customShowToast(S.of(context).enter_id);
      return;
    }
    final form = _formKey.currentState;
    if (form!.validate()) {
      await loading(_authentication, text: '');
      // customShowToast('认证成功!');
      // Navigator.of(context).pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).verify_identity,
        ),
      ),
      body: SafeArea(
        child: Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: ThemeColor.bkColorFFFFFF,
          ),
          child: widget.id == '1'
              ? Container(
                  padding: EdgeInsets.all(15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        S.of(context).basic_info,
                        style: TextStyle(
                          fontSize: 20,
                          color: ThemeColor.colorBlack100,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 20),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              S.of(context).name,
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack60,
                              ),
                            ),
                            Text(
                              UserInfo.me.cert.name,
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack100,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 20),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              S.of(context).id_number,
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack60,
                              ),
                            ),
                            Text(
                              UserInfo.me.cert.license_number.replaceRange(
                                  3,
                                  UserInfo.me.cert.license_number.length - 3,
                                  '*******'),
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack100,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                )
              : Form(
                  key: _formKey,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Container(
                        padding:
                            EdgeInsets.symmetric(horizontal: 30, vertical: 30),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              S.of(context).id_type,
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack100,
                              ),
                            ),
                            // SizedBox(
                            //   height: 4,
                            // ),
                            // Row(
                            //   children: [
                            //     Expanded(
                            //       flex: 1,
                            //       child: DropdownButtonFormField(
                            //         isExpanded: true,
                            //         alignment: AlignmentDirectional.centerStart,
                            //         icon: Icon(Icons.chevron_right),
                            //         decoration: InputDecoration(
                            //           border: InputBorder.none,
                            //           contentPadding:
                            //               EdgeInsets.fromLTRB(0, 0, 0, 0),
                            //         ),
                            //         value: certificate_type,
                            //         selectedItemBuilder: (context) {
                            //           return certificateData.map((label) {
                            //             return Text(
                            //               label.name,
                            //               maxLines: 2,
                            //               style: TextStyle(
                            //                 overflow: TextOverflow.visible,
                            //               ),
                            //               textAlign: TextAlign.left,
                            //             );
                            //           }).toList();
                            //         },
                            //         items: certificateData.map((label) {
                            //           return DropdownMenuItem(
                            //             child: Align(
                            //               alignment: Alignment.centerRight,
                            //               child: Text(
                            //                 label.name,
                            //                 textAlign: TextAlign.left,
                            //               ),
                            //             ),
                            //             value: label.id,
                            //           );
                            //         }).toList(),
                            //         hint: Text(''),
                            //         onChanged: (value) {
                            //           print(value);
                            //           setState(() {
                            //             certificate_type = value.toString();
                            //           });
                            //         },
                            //         onSaved: (value) {
                            //           certificate_type = value.toString();
                            //         },
                            //       ),
                            //     ),
                            //   ],
                            // ),
                            SizedBox(
                              height: 12,
                            ),
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                List lauguageArr = [];
                                for (CardsItemData element in certificateData) {
                                  lauguageArr.add(
                                      ChooseItemData(element.id, element.name));
                                }
                                //  = [
                                //   ChooseItemData('1', S().language_zh),
                                //   ChooseItemData('2', 'English'),
                                // ];
                                showCommonDialog(
                                  context,
                                  DialogEntity(
                                    S.of(context).id_type,
                                    RoleBox(RoleItemEntity(
                                      lauguageArr,
                                      (id, name) {
                                        print(
                                            "call back -0-------- $id -- $name");
                                        certificate_type = id;
                                        // selectName = name;
                                      },
                                      role: selectCertificate?.name ?? '',
                                    )),
                                    () {
                                      Navigator.of(context).pop();
                                    },
                                    () async {
                                      await Navigator.of(context).maybePop();
                                      for (var element in certificateData) {
                                        if (element.id == certificate_type) {
                                          selectCertificate = element;
                                        }
                                      }
                                      setState(() {
                                        // certificate_type = certificate_type.toString();
                                      });

                                      // String? local;
                                      // if (selectId == "1") {
                                      //   local = "zh";
                                      // } else if (selectId == "2") {
                                      //   local = "en";
                                      // } else if (selectId == "3") {
                                      //   local = "fr";
                                      // }
                                      // if (local != null) {
                                      //   S.delegate.load(Locale(local));
                                      //   appContext.storage.setString("storyLocal", local);
                                      //   if (UserInfo.me.isLogin) {
                                      //     await API.shared.user.updateUserInfo('lang', local);
                                      //   }
                                      // }
                                      // Navigator.of(context).pushReplacement(
                                      //   MaterialPageRoute(
                                      //     builder: (context) {
                                      //       return MainPage();
                                      //     },
                                      //   ),
                                      // );
                                    },
                                    contentPadding:
                                        EdgeInsets.fromLTRB(25, 20, 25, 20.0),
                                    cancelText: S.of(context).cancel,
                                    okText: S.of(context).sure,
                                  ),
                                );
                              },
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                      child: Text(
                                    selectCertificate?.name ?? '',
                                    style:
                                        TextStyle(fontWeight: FontWeight.w400),
                                  )),
                                  SizedBox(
                                    width: 10,
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    size: 14,
                                  )
                                ],
                              ),
                            ),
                            SizedBox(
                              height: 30,
                            ),
                            Text(
                              S.of(context).id_number,
                              style: TextStyle(
                                fontSize: 16,
                                color: ThemeColor.colorBlack80,
                              ),
                            ),
                            // SizedBox(
                            //   height: 12,
                            // ),
                            Row(
                              children: [
                                Expanded(
                                  flex: 1,
                                  child: TextFormField(
                                    enableInteractiveSelection: true,
                                    maxLength: 18,
                                    inputFormatters: [
                                      FilteringTextInputFormatter.deny(
                                          appContext.emojiRegexp)
                                    ],
                                    textAlign: TextAlign.left,
                                    decoration: InputDecoration(
                                      counterText: '',
                                      hintText: S.of(context).enter_id,
                                      border: InputBorder.none,
                                      isCollapsed: true,
                                      hintStyle: TextStyle(
                                          color: Colors.black.withOpacity(0.2)),
                                      contentPadding:
                                          EdgeInsets.symmetric(vertical: 10),
                                    ),
                                    onChanged: (value) {
                                      license_number = value;
                                    },
                                    onSaved: (value) {
                                      license_number = value.toString();
                                    },
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(height: 40),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(30, 12, 30, 12),
                        child: ElevatedButton(
                            child: Text(
                              S.of(context).continues,
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                                color: ThemeColor.colorBlack100,
                              ),
                            ),
                            onPressed: ClickUtils.debounce(
                              () async {
                                _submit();
                              },
                            )),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 30),
                        child: Text(
                          S.of(context).verify_tips,
                          style: TextStyle(
                            fontSize: 14,
                            color: ThemeColor.colorBlack40,
                          ),
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 30),
                        child: Text(
                          S.of(context).verify_tips1,
                          style: TextStyle(
                            fontSize: 14,
                            color: ThemeColor.colorBlack40,
                          ),
                        ),
                      )
                    ],
                  ),
                ),
        ),
      ),
    );
  }
}
